package apis

import (
	"go-admin/config"
	"net"
	"net/http"
	"net/url"

	"github.com/gin-gonic/gin"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/gorilla/websocket"
)

type SysAudio struct {
	api.Api
}

const (
	BufferSize = 1024 * 100
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func (e SysAudio) PushAudio(ctx *gin.Context) {
	// 升级连接
	ws, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		return
	}
	// 设置http上下文
	e.MakeContext(ctx)
	// 解析sip主机地址
	url, err := url.Parse(config.ExtConfig.GoSip.Api)
	if err != nil {
		e.Logger.Error("audio server url error,url:%s,err:%v", config.ExtConfig.GoSip.Api, err)
		ws.Close()
		return
	}
	ipaddr, err := net.ResolveIPAddr("ip", url.Hostname())
	if err != nil {
		e.Logger.Error("audio server ip error,url:%s,err:%v", config.ExtConfig.GoSip.Api, err)
		ws.Close()
		return
	}
	// 创建拉流客户端
	conn, err := net.Dial("tcp", ipaddr.IP.String()+":"+ctx.Param("port"))
	if err != nil {
		e.Logger.Error("连接语音推流服务器失败", err)
		ws.Close()
		conn.Close()
		return
	} else {
		e.Logger.Debugf("连接语音推流服务器成功,ip:%s,port:%s", ipaddr.IP.String(), ctx.Param("port"))
	}
	// 读取websocket数据
	e.readAudioFromWebsocket(ws, conn)
	ws.Close()
	conn.Close()
}

func (e SysAudio) readAudioFromWebsocket(ws *websocket.Conn, conn net.Conn) {
	for {
		t, bytes, err := ws.ReadMessage()
		if err != nil {
			e.Logger.Error("语音推流websocket连接关闭", err)
			break
		}
		if t == websocket.BinaryMessage {
			// 写入tcp连接
			_, err = conn.Write(bytes)
			if err != nil {
				e.Logger.Error("写入tcp连接失败", err)
				break
			}
		}
	}
}
